package ini

import (
	"io/ioutil"
	"runtime"
	"strings"
)

type Config struct {
	dict map[string]string
}

func (config Config) Get(key string) string {
	return config.dict[key]
}

var osCommentSign string

func init() {
	if runtime.GOOS == "windows" {
		osCommentSign = ";"
	}
	osCommentSign = "#"
}

func Parse(inifile string) (Config, error) {
	config := new(Config)
	config.dict = make(map[string]string)

	bytes, err := ioutil.ReadFile(inifile)
	if err != nil {
		return Config{}, &ErrOpenFile{err.Error()}
	}
	strlines := string(bytes)
	lines := strings.Split(strlines, "\n")
	for _, line := range lines {
		if idx := strings.Index(line, osCommentSign); idx != -1 {
			line = line[0:idx]
		}
		if strings.Index(line, "=") != -1 {
			tokens := strings.Fields(line)
			config.dict[tokens[0]] = tokens[2]
		}
	}

	return *config, nil
}
